package com.hualian.user.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.hualian.system.common.Constants;
import com.hualian.system.controller.BaseController;
import com.hualian.user.mapper.UserMapper;
import com.hualian.user.service.TeamService;
import com.hualian.user.service.UserService;
import com.hualian.util.http.MD5Util;

@RestController
@RequestMapping("/team")
public class TeamController extends BaseController {

	@Autowired
	private TeamService teamService;
	
	@Autowired
	private UserService userService;

	@Autowired
	private UserController userController;

	/**
	 * 跳转到队伍首页
	 * 
	 * @return
	 */
	@RequestMapping("/toTeamIndex")
	public ModelAndView toTeamIndex() {
		return new ModelAndView();
	}

	/**
	 * 用户查看队伍信息界面
	 * 
	 * @return
	 */
	@RequestMapping("/toMyTeam")
	public ModelAndView toMyTeam(HttpSession session) {
		Map<String, Object> team = getMyTeamBySession(session);
		return new ModelAndView("team/myTeam").addObject("team", team);
	}
	
	
	
	/**
	 * 用户查看查看队员信息
	 * 
	 * @return
	 */
	@RequestMapping("/toMyTeammate")
	public ModelAndView toMyTeammate(HttpSession session) {

		// 当前用户所在的队伍ID
		Integer teamId = getMyTeamIdBySession(session);
		List<Map<String, Object>> userList = new ArrayList<Map<String, Object>>();
		if (teamId != null) {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("teamId", teamId);
			userList = userService.getUser(params);
		}
		return new ModelAndView("team/myTeammate").addObject("userList", userList);
	}
	
	/**
	 * @param session
	 * @return
	 */
	@RequestMapping("getMyTeammate")
	public Map<String,Object> getMyTeammate(HttpSession session){
		Map<String,Object> jsonMap = new HashMap<String, Object>();
		//当前用户所在的队伍ID
		Integer  teamId =  getMyTeamIdBySession(session);
		if(teamId!=null){
			Map<String,Object> params = new HashMap<String, Object>();
			params.put("teamId", teamId);
			List<Map<String,Object>> userList =  userService.getUser(params);
			jsonMap.put(SUCCESS, true);
			jsonMap.put("userList", userList);
		}else{
			jsonMap.put(SUCCESS, false);
		}
		return jsonMap;
	}
	
	
	

	/**
	 * 获取本人加入的队伍信息
	 * 
	 * @param session
	 * @return
	 */
	public Map<String, Object> getMyTeamBySession(HttpSession session) {
		// TODO 增加判断 如果 没有加入队伍等等....

		// 获取用户信息
		Map<String, Object> userInfo = userController.getUserInfoBySession(session);
		Integer teamId = userInfo.get("teamId") == null ? null : Integer.valueOf(userInfo.get("teamId").toString());
		if (teamId != null) {
			return getMyTeamById(teamId);
		} 
		return null;
	}
	
	
	/**
	 * 根据主键查询队伍信息
	 * @param teamId
	 * @return
	 */
	public Map<String,Object> getMyTeamById(Integer id){
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", id);

		// 获取队伍信息
		List<Map<String, Object>> teamList = teamService.getTeam(params);
		if(teamList.size()>0){
			return teamList.get(0);
		}else{
			return null;
		}
	}
	
	

	/**
	 * 根据session获取队伍的主键
	 * 
	 * @param session
	 * @return
	 */
	public Integer getMyTeamIdBySession(HttpSession session) {
		return getMyTeamBySession(session)==null?null:Integer.valueOf(getMyTeamBySession(session).get("id").toString());
	}

	//
	// /**
	// * 用户获取队伍信息
	// * @param session
	// * @param request
	// * @return
	// */
	// @RequestMapping("/userGetTeam")
	// public Map<String,Object> getTeam (HttpSession session
	// ,HttpServletRequest request){
	// Map<String,Object> jsonMap = new HashMap<String, Object>();
	// Map<String,Object> params = super.convertParamToMap(request);
	// try{
	// List<Map<String,Object>> team = teamService.getTeam(params);
	// jsonMap.put(DATA, team);
	// jsonMap.put(SUCCESS, true);
	//
	// }catch(Exception e){
	// e.printStackTrace();
	// jsonMap.put(SUCCESS, false);
	// }
	// return null;
	// }

	/**
	 * 创建队伍
	 * code:队伍编码  name:队伍名称
	 * @param session
	 * @param request
	 * @return
	 */
	@RequestMapping("/addTeam")
	public Map<String, Object> addTeam(HttpSession session, HttpServletRequest request) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		Map<String, Object> params = super.convertParamToMap(request);
		try {
			
			//用户已经加入过队伍,退出该队伍之前不能重新加入队伍
			if(!userNotInTeam(session)){
				jsonMap.put(SUCCESS, false);
				jsonMap.put(ERROR_MSG, "用户已经有队伍了,无法创建队伍,如需创建请先退出队伍!");
				return jsonMap;
			}
			
			Map<String,Object> codeMap = new HashMap<String, Object>();
			codeMap.put("code", params.get("code"));
			//判断队伍编码是否重复
			if(!teamNotDuplicate(codeMap)){
				jsonMap.put(SUCCESS, false);
				jsonMap.put(ERROR_MSG, "队伍编码已经存在,请更换!");
				return jsonMap;
			}
			
			Map<String,Object> nameMap = new HashMap<String, Object>();
			nameMap.put("name", params.get("name"));
			//判断队伍编码是否重复
			if(!teamNotDuplicate(nameMap)){
				jsonMap.put(SUCCESS, false);
				jsonMap.put(ERROR_MSG, "队伍名称已经存在,请更换!");
				return jsonMap;
			}
			
			//当前用户主键
			Integer userId = userController.getUserIdBySession(session);
			
			params.put("captainId", userId);
			
			int num = teamService.addTeam(params,userId);
			if(num == 1){
				jsonMap.put(SUCCESS, true);
			}else{
				jsonMap.put(SUCCESS, false);
			}
		} catch (Exception e) {
			e.printStackTrace();
			jsonMap.put(SUCCESS, false);
		}

		return jsonMap;
	}
	
	
	/**
	 * 根据传入的参数判断队伍是否重复
	 * code:队伍编码  name:队伍名称
	 * @param params
	 * @return
	 */
	public boolean teamNotDuplicate(Map<String, Object> params) {

		List<Map<String, Object>> teamList = teamService.getTeam(params);

		if (teamList.size() > 0) {
			return false;
		} else {
			return true;
		}
	}
	

	/**
	 * 修改队伍信息
	 * 
	 * @param session
	 * @param request
	 * @return
	 */
	@RequestMapping("/updateTeam")
	public Map<String, Object> updateTeam(HttpSession session, HttpServletRequest request) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		Map<String, Object> params = super.convertParamToMap(request);
		try {
			// TODO 队伍编码只能修改一次
			teamService.updateTeam(params);

			jsonMap.put(SUCCESS, true);
		} catch (Exception e) {
			e.printStackTrace();
			jsonMap.put(SUCCESS, false);
		}

		return jsonMap;
	}

	/**
	 * 删除队伍
	 * 
	 * @param session
	 * @param request
	 * @return
	 */
	@RequestMapping("/removeTeam")
	public Map<String, Object> removeTeam(HttpSession session, HttpServletRequest request) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		Map<String, Object> params = super.convertParamToMap(request);
		try {

			// TODO 如果队伍中有其他成员,则不可删除

			//teamService.removeTeam(params);

			jsonMap.put(SUCCESS, true);
		} catch (Exception e) {
			e.printStackTrace();
			jsonMap.put(SUCCESS, false);
		}

		return jsonMap;
	}

	/**
	 * 添加队伍成员 传入参数: userId:用户表主键,teamId:队伍表主键
	 * 
	 * @param session
	 * @param request
	 * @return
	 */
	@RequestMapping("/addMember")
	public Map<String, Object> addMember(HttpSession session, HttpServletRequest request) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		//TODO 选择用户添加  被添加用户确认 之后加入
		return jsonMap;
	}
	
	
	
	/**
	 * localhost:8080/crm/team/joinTeam?teamId=8&&timeStamp=1452764099883&&validateCode=b2c9xbdc76Nz29dNcea026ffb3Na6fNN
	 * 通过扫描二维码加入队伍
	 * 传入参数: teamId:队伍ID, timeStamp:时间戳
	 * @param session
	 * @param request
	 * @return
	 */
	@RequestMapping("/joinTeam")
	public Map<String, Object> joinTeam(HttpSession session, HttpServletRequest request) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		Map<String, Object> params = super.convertParamToMap(request);
		try {
			//队伍主键
			Integer teamId = Integer.valueOf(params.get("teamId").toString());
			//时间戳
			Long timeStamp = Long.valueOf(params.get("timeStamp").toString());
			//校验信息
			String validateCode = params.get("validateCode").toString();
			
			if(teamId==null||timeStamp==null||validateCode==null){
				jsonMap.put(SUCCESS, false);
				jsonMap.put(ERROR_MSG, "加入队伍失败,二维码有误!");
				return jsonMap;
			}
			
			//即将加入的队伍的信息
			Map<String,Object> teamInfo = getMyTeamById(teamId);
			//即将加入的队伍的队长的主键
			Integer captainId = Integer.valueOf(teamInfo.get("captainId").toString());
			
			String  validateCode_ = getJoinTeamValidateCode(teamId, captainId, timeStamp);
			
			if(!validateCode_.equals(validateCode)){
				jsonMap.put(SUCCESS, false);
				jsonMap.put(ERROR_MSG, "加入队伍失败,二维码有误!");
				return jsonMap;
			}
			
			
			//如果系统参数 JOIN_TEAM_QRCODE_INDATE 不设置为 EVER,则进行二维码失效期限判断
			if(!"EVER".equals(super.getParameterByCode(Constants.JOIN_TEAM_QRCODE_INDATE))){
				//二维码有效期
				Long QRCodeIndate =  Long.valueOf(super.getParameterByCode(Constants.JOIN_TEAM_QRCODE_INDATE) == null ? Constants.JOIN_TEAM_QRCODE_INDATE_DEFAULT : super.getParameterByCode(Constants.JOIN_TEAM_QRCODE_INDATE));
				
				
				//当前时间
				Long now = System.currentTimeMillis();
				
				//根据二维码的时间戳判断二维码是否过期了
				if((now - timeStamp)/1000/60 > QRCodeIndate){
					
					jsonMap.put(SUCCESS, false);
					jsonMap.put(ERROR_MSG, "加入队伍失败,二维码过期");
					return jsonMap;
				}
			}
			
			//用户已经加入过队伍,退出该队伍之前不能重新加入队伍
			if(!userNotInTeam(session)){
				jsonMap.put(SUCCESS, false);
				jsonMap.put(ERROR_MSG, "用户已经加入队伍,不能加入该队伍,如果想加入该队伍,请先退出原来的队伍!");
				return jsonMap;
			}
			
			// 通过session获取用户主键
			Integer userId = userController.getUserIdBySession(session);
			//设置当前登陆的用户主键
			params.put("userId", userId);
			
			// 队伍允许的最大人数
			int teamMaxQuantity = Integer.valueOf(super.getParameterByCode(Constants.TEAM_MAX_QUANTITY) == null ? Constants.TEAM_MAX_QUANTITY_DEFAULT : super.getParameterByCode(Constants.TEAM_MAX_QUANTITY));

			// 将用户表中 team_id 更新,并更新队伍表中人数,并查看是否已经人满, 记录用户加入队伍日志
			int num = teamService.addMember(params, teamMaxQuantity);

			// TODO 队伍人员满员时,给邀请创建队伍的队伍以及上级队伍发放佣金 (第一次满员有效)
			
			
			
			
			if (num == 1) {
				jsonMap.put(SUCCESS, true);
			} else if(num == Constants.TEAM_IS_FULL){
				jsonMap.put(SUCCESS, false);
				jsonMap.put(ERROR_MSG, "该队伍人员已经满了!");
			}else if( num == Constants.TEAM_NOT_EXISTS){
				jsonMap.put(SUCCESS, false);
				jsonMap.put(ERROR_MSG, "该队伍不存在!");
			}else{
				jsonMap.put(SUCCESS, false);
				jsonMap.put(ERROR_MSG, "加入队伍失败!");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			jsonMap.put(SUCCESS, false);
			jsonMap.put(ERROR_MSG, "加入队伍失败!");
		}

		return jsonMap;
	}
	
	/**
	 * 根据session判断用户当前有没有加入队伍
	 * true:用户没有加入任何队伍, false:用户加入了队伍
	 * @param session
	 * @return
	 */
	public boolean userNotInTeam(HttpSession session) {

		// 用户信息
		Map<String, Object> userInfo = userController.getUserInfoBySession(session);

		// 用户已经加入过队伍,退出该队伍之前不能重新加入队伍
		if (userInfo.get("teamId") != null && !Constants.USER_NOT_JOIN_TEAM.equals(userInfo.get("teamId").toString())) {

			return false;
		} else {
			return true;
		}
	}
	
	
	
	
	/**
	 * 自己离开队伍 
	 * 
	 * @param session
	 * @param request
	 * @return
	 */
	@RequestMapping("/leaveTeam")
	public Map<String, Object> leaveTeam(HttpSession session) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		Map<String, Object> params = new HashMap<String, Object>();
		
		//TODO 队长离开队伍 委任队长  以及 最后一个人离开队伍  队伍解散等问题
		
		// 通过session获取用户主键
		Integer userId = userController.getUserIdBySession(session);
		// 通过session获取用户队伍主键
		Integer teamId = getMyTeamIdBySession(session);
		
		//队伍信息
		Map<String,Object> teamInfo = getMyTeamBySession(session);
		if(Integer.valueOf(teamInfo.get("quantity").toString())!=1&&userController.isCaptainBySession(session)){
			jsonMap.put(SUCCESS, false);
			jsonMap.put(ERROR_MSG, "请您先将队长委任给他人,再退出队伍!");
			return jsonMap;
		}
		

		if(teamId==null){
			jsonMap.put(SUCCESS, false);
			jsonMap.put(ERROR_MSG, "没有队伍可以离开!");
			return jsonMap;
		}
	
		params.put("userId", userId);
		params.put("teamId", teamId);
		try {

			// 将用户表中 team_id 更新,并更新队伍表中队伍人数,记录用户离开队伍日志
			teamService.removeMember(params,teamInfo);

			jsonMap.put(SUCCESS, true);
		} catch (Exception e) {
			e.printStackTrace();
			jsonMap.put(SUCCESS, false);
		}

		return jsonMap;
	}
	
	
	
	/**
	 * 强制踢人  
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping("/removeMember")
	public Map<String,Object> removeMember(HttpServletRequest request,HttpSession session){
		//TODO 踢人之前必须把账户里面的钱平分  分钱策略: 平分强制无异议 和 平分也需要全票通过
		
		return null;
	}

	/**
	 * 生成邀请别人加入队伍的二维码
	 * @return
	 */
	@RequestMapping("/getInviteQRCode")
	public Map<String,Object> getInviteQRCode(HttpSession session ){
		Map<String,Object> jsonMap= new HashMap<String, Object>();
		
		//队伍信息
		Map<String,Object> teamInfo = getMyTeamBySession(session);
		if(teamInfo!=null){
			//队伍主键
			Integer teamId = getMyTeamIdBySession(session);
			//队长ID
			Integer captainId = teamInfo==null?null: Integer.valueOf(teamInfo.get("captainId").toString());
			
			long now = System.currentTimeMillis();
			String validateCode = getJoinTeamValidateCode(teamId,captainId,now);
			
			//生成的邀请别人进组的链接
			String url = Constants.BASE_PATH+"/team/joinTeam?teamId="+teamId+"&&timeStamp="+now+"&&validateCode="+validateCode;
			System.out.println("url:"+url);
			
			jsonMap.put(SUCCESS, true);
			jsonMap.put("url", url);
		}else{
			jsonMap.put(SUCCESS, false);
			jsonMap.put(ERROR_MSG, "没有队伍不能生成邀请的二维码!");
		}
		
		return jsonMap;
		
	}
	
	/**
	 * 将传进来的 teamId captainId timeStamp 进行md5 加密
	 * @param teamId
	 * @param captainId
	 * @param timeStamp
	 * @return
	 */
	public String getJoinTeamValidateCode(Integer teamId , Integer captainId ,long timeStamp){
		String validateCode = teamId+captainId+String.valueOf(timeStamp);
		return MD5Util.md5(validateCode);
	}
	
	/**
	 * 传入的参数  newCaptainId :新队长的主键
	 * 委任队长
	 * @return
	 */
	@RequestMapping("/appointCaptain")
	public Map<String,Object> appointCaptain(HttpServletRequest request,HttpSession session	){
		Map<String,Object> jsonMap = new HashMap<String, Object>();
		Map<String,Object> params = convertParamToMap(request);
		//当前用户主键
		Integer userId = userController.getUserIdBySession(session);
		//当前用户信息
		Map<String,Object> userInfo = userController.getUserInfoBySession(session);
		//当前用户队伍主键
		Integer teamId = getMyTeamIdBySession(session);
		//如果用户不是队长,则无法委任队长
		if(!userController.isCaptainBySession(session)){
			jsonMap.put(SUCCESS, false); 
			jsonMap.put(ERROR_MSG, "抱歉您不是队长,无法委任队长!");
			return jsonMap;
		}
		
		if(userId == Integer.valueOf(params.get("newCaptainId").toString())){
			jsonMap.put(SUCCESS, false); 
			jsonMap.put(ERROR_MSG, "您已经是队长了,无需委任自己!");
			return jsonMap;
		}
		
		
		params.put("userId", userId);
		params.put("teamId", teamId);
		int rows = teamService.appointCaptain(params);
		
		if(rows==1){
			jsonMap.put(SUCCESS, true); 
		}else{
			jsonMap.put(SUCCESS, false); 
		}
		
		return jsonMap;
	}
	
	
	
}
